<style lang="sass">
.imgDetail
  width: 100%
  height: 100vh
  padding: 0
  margin: 0
  position: relative
  .img
    border: none
    margin: 0
    padding: 0
    width: 100%
    height: 100%
  .operation
    position: absolute
    right: 20px
    bottom: 120px
    display: flex
    flex-direction: column
    width: 120px
    .operationItem
      background-color: rgba(0, 0, 0, 0.49)
      margin-bottom: 40px
      display: flex
      align-items: center
      justify-content: center
      width: 120px
      height: 120px
      color: #fff
      border-radius: 60px
</style>
<template>
  <view class="imgDetail">
    <Image class="img" mode="aspectFit" :src="detail.hdPath"/>
    <view class="operation">
      <view class="operationItem" v-if="platForm == 'tt'" @tap="ttDownload">下载</view>
      <view class="operationItem" v-if="platForm == 'weapp'" @tap="weappDownload">下载</view>
<!--      <view class="operationItem">分享</view>-->
    </view>
  </view>
</template>

<script setup>

import Taro, {useLoad} from "@tarojs/taro";
import {reactive, ref} from "vue";
import {get} from "../../util/request";
import {Image} from "@tarojs/components";
const detail = reactive({})

const getDetail = async (id) => {
  const result = await get('img', {
    id: id
  })
  Object.assign(detail, result)
}
getDetail(Taro.getCurrentInstance().router.params.id)
const platForm = process.env.TARO_ENV;
const videoAd = ref(null)
useLoad(() => {
  if (process.env.TARO_ENV === 'tt') {
    adLock.value = true
    videoAd.value = Taro.createRewardedVideoAd({
      adUnitId: 'c9tw9z1qq5cjvjka36'
    })
    videoAd.value.onError((err) => {
      videoAd.value.load()
      videoAd.value.show()
    });
    videoAd.value.onClose(closeHandle)
    videoAd.value.load()
  }
})

const adLock = ref(true)
const closeHandle = ({isEnded}) => {
  if (isEnded) {
    adLock.value = false
    downloadFile()
  }
}
const ttDownload = async () => {
  if (adLock.value) {
    Taro.showLoading({
      title: "加载中...",
      mask: true
    })
    videoAd.value.show().then(() => {
      Taro.hideLoading()
    }).catch((err) => {
      Taro.hideLoading()
    });
  }
}
const downloading = ref(false)
const downloadFile = async () => {
  if (downloading.value) return
  downloading.value = true
  Taro.showToast({
    title: "下载中",
    icon: "loading"
  })
  Taro.downloadFile({
    url: encodeURI(detail.hdPath),
    success: (res) => {
      Taro.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success: (data) => {
          Taro.showModal({
            content: "成功保存至手机相册",
            showCancel: false,
          });
          Taro.hideToast()
          downloading.value = false
        },
        fail: (res) => {
          Taro.showModal({
            content: "保存失败,打开相册权限",
            showCancel: false,
          });
          Taro.hideToast()
          downloading.value = false
        }
      })
    }
  })
}
const weappDownload = async () => {
  downloadFile()
}

</script>
